package com.test.mweb;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.client.elc.NativeQueryBuilder;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.SearchScrollHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;

import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;

@Service
public class NutchService {

	@Autowired
	private NutchRepository nutchRepository;

	@Autowired
	public ElasticsearchTemplate elasticsearchTemplate;

	public Page<Nutch> search(String content) {
		Pageable page = PageRequest.of(1, 10);
		IndexCoordinates index = IndexCoordinates.of("nutch");
		QueryBuilders.matchAll().build();
		Query query = new NativeQueryBuilder()
				.withQuery(QueryBuilders.match().field("content").query(content).build()._toQuery())
				.withPageable(page)
				.build();
		SearchScrollHits<Nutch> scroll = elasticsearchTemplate.searchScrollStart(1000, query, Nutch.class, index);
		long totole = scroll.getTotalHits();
		String scrollId = scroll.getScrollId();
		List<Nutch> sampleEntities = new ArrayList<>();
		while (scroll.hasSearchHits()) {
		  sampleEntities.addAll(scroll.getSearchHits().stream().map(item -> item.getContent()).collect(Collectors.toList()));
		  scrollId = scroll.getScrollId();
		  scroll = elasticsearchTemplate.searchScrollContinue(scrollId, 1000, Nutch.class, index);
		}
		elasticsearchTemplate.searchScrollClear(scrollId);
		return new PageImpl<>(sampleEntities, page, totole);
	}

	
	
	
	public Page<Nutch> page(String content) {
		Pageable page = PageRequest.of(1, 10);
		Query query = new NativeQueryBuilder()
				.withQuery(QueryBuilders.match().field("content").query(content).build()._toQuery()).withPageable(page)
				.build();
		SearchHits<Nutch> hits = elasticsearchTemplate.search(query, Nutch.class);
		return new PageImpl<>(hits.getSearchHits().stream().map(item -> item.getContent()).collect(Collectors.toList()),
				page, hits.getTotalHits());
	}
}
